package com.k.activemq.openwire;

import com.k.activemq.MqConnectionEntity;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.nio.charset.StandardCharsets;

public class Publisher {

    public static void main(String[] args) throws JMSException {
        MqConnectionEntity connectionEntity = MqConnectionEntity.newBuilder()
                .setUrl("tcp://localhost:61616")
                .setUsername("admin")
                .setPassword("admin")
                .setDestination("kpp-test1-byte")
                .setPubSubDomain(true)
                .setMessage("hello")
                .setByteMessage(true)
                .build();
        pushToMq(connectionEntity);
    }

    private static void pushToMq(MqConnectionEntity et) throws JMSException {
        // 1.connectionFactory
        ConnectionFactory factory = new ActiveMQConnectionFactory(et.getUrl());

        // 2. connection
        Connection connection = factory.createConnection(et.getUsername(), et.getPassword());
        connection.start();

        // 3. session
        // param1: isSessionTransacted,
        // param2: int AUTO_ACKNOWLEDGE = 1;int CLIENT_ACKNOWLEDGE = 2;int DUPS_OK_ACKNOWLEDGE = 3;
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

        // 4. destination
        Destination dest = (et.getPubSubDomain())? session.createTopic(et.getDestination()):session.createQueue(et.getDestination());

        // 5. producer
        MessageProducer producer = session.createProducer(dest);
        producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
        producer.setTimeToLive(1000 * 6);
        producer.setPriority(1);
        if(et.getByteMessage()){
            System.out.println("send byteMsg:"+et.getMessage());
            byte[] byteMsg = et.getMessage().getBytes(StandardCharsets.UTF_8);
            BytesMessage msg = session.createBytesMessage();
            msg.writeBytes(byteMsg);
            producer.send(msg);
            System.out.println("send byteMsg Ok");
        }else{
            for( int i=1; i <= 100; i ++) {
                TextMessage msg = session.createTextMessage(i+"-hello");
                msg.setIntProperty("id", i);
                producer.send(msg);
                if( (i % 100) == 0) {
                    System.out.println(String.format("Sent %d messages", i));
                }
            }
        }
        producer.send(session.createTextMessage("SHUTDOWN"));
        connection.close();
    }

}
